<template>
  <div class="demo-inspection-page">
    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" inline>
        <el-form-item label="检查名称">
          <el-input
            v-model="queryForm.inspectionName"
            placeholder="请输入检查名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="检查类型">
          <el-select
            v-model="queryForm.inspectionType"
            placeholder="请选择检查类型"
            clearable
            style="width: 150px"
          >
            <el-option label="安全检查" value="safety" />
            <el-option label="质量检查" value="quality" />
            <el-option label="环保检查" value="environmental" />
            <el-option label="运行检查" value="operation" />
            <el-option label="综合检查" value="comprehensive" />
          </el-select>
        </el-form-item>
        <el-form-item label="检查状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择检查状态"
            clearable
            style="width: 120px"
          >
            <el-option label="计划中" value="planning" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="paused" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="检查日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增检查</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="!selectedRows.length" @click="handleBatchDelete">批量删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Download" @click="handleExport">导出数据</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="inspectionCode" label="检查编号" width="120" />
        <el-table-column prop="inspectionName" label="检查名称" width="200" />
        <el-table-column prop="inspectionType" label="检查类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.inspectionType)">
              {{ getTypeText(row.inspectionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="检查级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="inspector" label="检查人员" width="120" />
        <el-table-column prop="inspectionDate" label="检查日期" width="120" />
        <el-table-column prop="location" label="检查地点" width="150" />
        <el-table-column prop="status" label="检查状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="检查评分" width="100" />
        <el-table-column prop="problemCount" label="问题数量" width="100" />
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="warning" icon="Document" @click="handleReport(scope.row)">报告</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <Pagination
          :total="pagination.total"
          v-model:page="pagination.currentPage"
          v-model:limit="pagination.pageSize"
          @pagination="handlePagination"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <DemoInspectionFormDialog
      v-model:visible="dialogVisible"
      :form-data="currentRow"
      :is-view="isView"
      @success="handleDialogSuccess"
    />

    <!-- 报告弹窗 -->
    <InspectionReportDialog
      v-model:visible="reportDialogVisible"
      :inspection-data="currentRow"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DemoInspectionFormDialog from './components/DemoInspectionFormDialog.vue'
import InspectionReportDialog from './components/InspectionReportDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 查询表单
const queryForm = reactive({
  inspectionName: '',
  inspectionType: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])
const allData = ref([] as any[])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const reportDialogVisible = ref(false)
const currentRow = ref(null)
const isView = ref(false)

// 获取类型标签样式
const getTypeTagType = (type: string) => {
  const typeMap = {
    'safety': 'danger',
    'quality': 'warning',
    'environmental': 'success',
    'operation': 'primary',
    'comprehensive': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap = {
    'safety': '安全检查',
    'quality': '质量检查',
    'environmental': '环保检查',
    'operation': '运行检查',
    'comprehensive': '综合检查'
  }
  return typeMap[type] || type
}

// 获取级别标签样式
const getLevelTagType = (level: string) => {
  const levelMap = {
    'A': 'danger',
    'B': 'warning',
    'C': 'primary',
    'D': 'success'
  }
  return levelMap[level] || 'info'
}

// 获取级别文本
const getLevelText = (level: string) => {
  const levelMap = {
    'A': 'A级',
    'B': 'B级',
    'C': 'C级',
    'D': 'D级'
  }
  return levelMap[level] || level
}

// 获取状态标签样式
const getStatusTagType = (status: string) => {
  const statusMap = {
    planning: 'info',
    ongoing: 'primary',
    completed: 'success',
    paused: 'warning',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    planning: '计划中',
    ongoing: '进行中',
    completed: '已完成',
    paused: '已暂停',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 生成伪数据
const randomChoice = (arr: any[]) => arr[Math.floor(Math.random() * arr.length)]
const generateMockData = (count: number) => {
  const types = ['safety', 'quality', 'environmental', 'operation', 'comprehensive']
  const levels = ['A', 'B', 'C', 'D']
  const statuses = ['planning', 'ongoing', 'completed', 'paused', 'cancelled']
  const locations = ['水库大坝', '机房设备区', '闸门控制室', '输水管道区', '库区周边']
  const names = ['张三', '李四', '王五', '赵六', '钱七']
  const list = [] as any[]
  for (let i = 0; i < count; i++) {
    const id = i + 1
    const type = randomChoice(types)
    const level = randomChoice(levels)
    const status = randomChoice(statuses)
    const inspector = randomChoice(names)
    const date = new Date(2024, Math.floor(Math.random() * 6) + 1, Math.floor(Math.random() * 28) + 1)
    list.push({
      id,
      inspectionCode: `DI2024${String(id).padStart(3, '0')}`,
      inspectionName: `${getTypeText(type)}示范检查${id}`,
      inspectionType: type,
      level,
      inspector,
      inspectionDate: `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`,
      location: randomChoice(locations),
      status,
      score: status === 'completed' ? Math.floor(Math.random() * 21) + 80 : 0,
      problemCount: status === 'completed' ? Math.floor(Math.random() * 6) : Math.floor(Math.random() * 3),
      department: '安全监察部',
      phone: '13800138000',
      email: 'demo@example.com',
      startTime: '09:00',
      endTime: '17:00',
      participants: '张三、李四、王五',
      objective: '示范检查目标',
      scope: '示范检查范围',
      method: '现场检查、仪器检测、资料审查',
      standards: '《水库大坝安全管理条例》',
      findings: '发现若干需要处理的问题',
      suggestions: '建议加强日常巡查，定期维护',
      conclusion: '整体情况良好',
      remark: '示范检查记录'
    })
  }
  return list
}

// 根据查询与分页应用数据
const applyFiltersAndPaginate = () => {
  const { inspectionName, inspectionType, status } = queryForm
  const filtered = allData.value.filter((item) => {
    const matchName = inspectionName ? item.inspectionName.includes(inspectionName) : true
    const matchType = inspectionType ? item.inspectionType === inspectionType : true
    const matchStatus = status ? item.status === status : true
    return matchName && matchType && matchStatus
  })
  pagination.total = filtered.length
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  tableData.value = filtered.slice(start, end)
}

// 模拟API - 获取示范检查列表
const fetchDemoInspectionList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    const count = Math.floor(Math.random() * 41) + 10 // 10-50条
    allData.value = generateMockData(count)
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 模拟API - 删除示范检查
const deleteDemoInspection = async (ids: number[]) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 200))
    allData.value = allData.value.filter(item => !ids.includes(item.id))
    applyFiltersAndPaginate()
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    inspectionName: '',
    inspectionType: '',
    status: '',
    dateRange: []
  })
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 分页处理
const handlePagination = (page: any) => {
  pagination.currentPage = page.page
  pagination.pageSize = page.limit
  applyFiltersAndPaginate()
}

// 弹窗成功回调
const handleDialogSuccess = () => {
  // 简单处理：重新生成并应用数据
  fetchDemoInspectionList()
}

// 初始化
onMounted(() => {
  fetchDemoInspectionList()
})
</script>

<style scoped>
.demo-inspection-page {
  padding: 20px;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>